<template>
  <div class="select-class">
    <h5 class="subtitle">最后一步</h5>
    <cube-form :model="model" @validate="validateHandler" @submit="submitHandler">
      <cube-form-group>
        <cube-form-item :field="fields[0]">
          <div class="selectedVal" @click="showSchoolPicker">
            <span v-if="model.className==''" class="placeholder">请选择班级</span>
            <span v-if="model.className!=''">{{model.className}}</span>
          </div>
        </cube-form-item>
        <cube-form-item :field="fields[1]"></cube-form-item>
      </cube-form-group>
      <cube-form-group class="subBtn">
        <cube-button @click="goback" :inline="true" :primary="true">上一步</cube-button>
        <cube-button type="submit" :inline="true" :primary="true">提交</cube-button>
      </cube-form-group>
    </cube-form>
  </div>
</template>

<script>
export default {
  name: "SelectClass",
  data() {
    return {
      validity: {},
      valid: undefined,
      model: {
        gradeId: "",
        className: "",
        stuAccount: ""
      },
      fields: [
        {
          modelKey: "className",
          label: "选择班级",
          props: {
            placeholder: "请选择班级"
          },
          rules: {
            required: true
          },
          messages: {
            required: "请选择所在班级"
          },
          events: {}
        },
        {
          type: "input",
          modelKey: "stuAccount",
          label: "学生账号",
          props: {
            placeholder: "请输入学生账号"
          },
          rules: {
            required: true
          },
          // validating when blur
          trigger: "blur"
        }
      ],
      content: ""
    };
  },
  created() {
    // console.log(localStorage.getItem("openID"));
    if (!localStorage.getItem("openID")) {
      this.getCode();
    }
  },
  mounted() {
    // console.log(JSON.parse(localStorage.getItem("classes")));
    this.setDataPicker = this.$createCascadePicker({
      title: "选择所在班级",
      data: JSON.parse(localStorage.getItem("classes")),
      alias: {
        value: "id",
        text: "gradeStr"
      },
      onSelect: this.selectHandle,
      onCancel: this.cancelHandle
    });
  },
  methods: {
    getUrlKey(name) {
      //获取url 参数
      return (
        decodeURIComponent(
          (new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(
            location.href
          ) || [, ""])[1].replace(/\+/g, "%20")
        ) || null
      );
    },
    getCode() {
      const code = this.getUrlKey("code"); // 截取路径中的code，如果没有就去微信授权，如果已经获取到了就直接传code给后台获取openId
      const local = window.location.href;
      const appid = "wx6d7dcd07ca4fa211";
      if (code == null || code === "") {
        window.location.href =
          "http://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
          appid +
          "&redirect_uri=" +
          encodeURIComponent(local) +
          "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
      } else {
        this.getOpenId(code); //把code传给后台获取用户信息
      }
    },
    async getOpenId(code) {
      // 通过code获取 openId等用户信息，/oauth2/printOpenID 为后台接口
      await this.$http
        .post("/oauth2/printOpenID", { code: code })
        .then(res => {
          let openID = res.data;
          this.$store.state.openID = openID;
          localStorage.setItem("openID", openID);
        })
        .catch(error => {
          console.log(error);
        });
    },

    showSchoolPicker() {
      this.setDataPicker.show();
    },
    selectHandle(selectedVal, selectedIndex, selectedText) {
      this.model.className = selectedText[0];
      this.model.gradeId = selectedVal[0];
    },
    cancelHandle() {
      this.$createToast({
        type: "correct",
        txt: "取消选择",
        time: 1000
      }).show();
    },
    validateHandler(result) {
      this.validity = result.validity;
      this.valid = result.valid;
    },
    submitHandler(e) {
      e.preventDefault();
      this.$store.state.gradeId = this.model.gradeId;
      this.$store.state.studentAccount = this.model.stuAccount;
      let requestData = {
        gradeId: this.$store.state.gradeId,
        studentAccount: this.$store.state.studentAccount
      };
      // 获取学生信息，绑定家长openid
      this.getStuInfor(requestData);
    },
    // 获取即将绑定的学生信息
    getStuInfor(requestData) {
      this.$http
        .post("/api000013", requestData)
        .then(response => {
          if (response.data.status == 0) {
            this.$createToast({
              type: "warn",
              time: 3000,
              txt: response.data.msg
            }).show();
          } else {
            this.content = response.data[0].name;
            this.$createDialog({
              type: "confirm",
              icon: "cubeic-alert",
              title: "您将绑定的学生姓名为",
              content: `${this.content}`,
              confirmBtn: {
                text: "确定",
                active: true,
                disabled: false,
                href: "javascript:;"
              },
              cancelBtn: {
                text: "取消",
                active: false,
                disabled: false,
                href: "javascript:;"
              },
              // 确定绑定
              onConfirm: () => {
                // console.log(localStorage.getItem("openID"))
                let requestData = {
                  openId: localStorage.getItem("openID"),
                  schoolId: response.data[0].schoolId,
                  studentIds: response.data[0].id,
                  parent: this.content + "的家长"
                };
                this.confirmBind(requestData);
              },
              // 取消绑定
              onCancel: () => {
                this.$createToast({
                  type: "warn",
                  time: 1000,
                  txt: "取消绑定"
                }).show();
              }
            }).show();
          }
        })
        .catch(function(error) {
          this.$createToast({
            type: "warn",
            time: 1000,
            txt: error
          }).show();
        });
    },
    // 确认绑定学生操作
    confirmBind(requestData) {
      this.$http
        .post("/api000014", requestData)
        .then(response => {
          // localStorage.setItem("openID", response.data.openID);
          if (response.data.status === "error") {
            this.$createToast({
              type: "loading",
              time: 1000,
              txt: "关系已绑定，即将跳转学生作业信息"
            }).show();
          } else if (response.data.status === "success") {
            this.$createToast({
              type: "loading",
              time: 1000,
              txt: "绑定成功，即将跳转学生作业信息"
            }).show();
          }
          setTimeout(() => {
            this.$router.push({
              path: "/parjoblist",
              query: {
                openID: localStorage.getItem("openID")
              }
            });
          }, 1000);
        })
        .catch(error => {
          this.$createToast({
            type: "warn",
            time: 1000,
            txt: error
          }).show();
        });
    },
    goback() {
      this.$router.push({
        path: "/paradd/year"
      });
    }
  }
};
</script>

<style lang="scss">
.select-class {
  .subtitle {
    font-size: 16px;
    font-weight: 700;
    color: #fc9153;
    margin-top: 20%;
    margin-bottom: 10%;
    text-align: center;
  }
  /* //设置存储picker选择获取的值的div的样式 */
  .selectedVal {
    text-align: left;
    /* 设置存储picker选择获取的值的div显示placeholder时字体的颜色 */
    .placeholder {
      color: #ccc;
    }
  }
  .subBtn {
    margin: 5% auto;
    text-align: center;
    margin-top: 20%;
    button {
      width: 40%;
      margin: 2%;
    }
  }
}
</style>